package com.suyx.job.controller;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.suyx.job.entity.JobInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.entity.Result;
import com.suyx.job.entity.GoodsInfo;
import com.suyx.job.service.IGoodsInfoService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/31 0031 10:10
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController  {

    private IGoodsInfoService goodsService;

    @Autowired
    public GoodsController(IGoodsInfoService goodsService) {
        this.goodsService = goodsService;
    }
    /**
     * 查询物品信息
     */
    @GetMapping(value="/findGoodsPage")
    public Page findGoodsPage(GoodsInfo goodsInfo, Integer page, Integer limit)
    {
        return goodsService.findGoodsPage(goodsInfo,page-1,limit);
    }

    /**
     * 保存物品信息
     */
    @PostMapping("/saveGoods")
    public Result saveGoods(GoodsInfo goodsInfo){
        try {
        	goodsService.saveAndFlush(goodsInfo);
            return new Result(true,"保存成功!");
        }catch (Exception e){
            log.error("保存物品信息数据报错："+ExceptionUtils.getStackTrace(e));
            return new Result(false,"保存失败："+e.getMessage());
        }
    }

    /**
     * 删除物品信息
     */
    @PostMapping("deleteGoods")
    public Result deleteGoods(Integer goodsId){
        try {
        	goodsService.deleteById(goodsId);
            return new Result(true,"删除成功!");
        }catch (Exception e){
            log.error("删除物品信息数据报错：" + ExceptionUtils.getStackTrace(e));
            return new Result(false,"删除失败："+e.getMessage());
        }
    }

    @PostMapping(value = "/updateStatus")
    public Result updateStatus(Integer goodsId, String status) {
        try {
        	GoodsInfo goodsInfo = goodsService.getOne(goodsId);
            if (goodsInfo == null) {
                return new Result(false, "该id值不存在！操作失败");
            }
            goodsInfo.setStatus(status);
            goodsService.saveAndFlush(goodsInfo);
            return new Result(true, "操作成功！");
        } catch (Exception e) {
            log.error("出现异常！" + ExceptionUtils.getStackTrace(e));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//捕获异常后进行回滚
            return new Result(false, "出现异常！" + e.getMessage());
        }
    }


}
